package cn.edu.scut.hsrc.synonymity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 同义词词林映射类
 * @file SynMaps.java
 * @author feiyu
 *
 */

public class SynMaps {
	private static Map<String, List<SynCode>> synonymitys = new HashMap<String, List<SynCode>>();	//同义词词林中词的映射<词，词所属的类别代码>
	private static SynMaps instance = null;
	static{
		//读取同义词词林里面的数据
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();;
		if (classLoader == null) {
			classLoader = ClassLoader.getSystemClassLoader();
		}
		URL url = classLoader.getResource("synonymity.txt");
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(),"utf-8"));
			while (reader.ready()) {
				String line = reader.readLine();
				String [] arrays = line.split(" +");
				String word = arrays[0];
				int num = Integer.parseInt(arrays[1])+2;
				List<SynCode> codes = new ArrayList<SynCode>();
				for(int i=2;i<num;i++)
				{
					codes.add(new SynCode(arrays[i]));
				}
				SynMaps.synonymitys.put(word, codes);
			}
			System.out.println("load synonymity dictionary: "+SynMaps.synonymitys.size()+" words");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @return
	 */
	public static SynMaps getInstance()
	{
		if(instance == null)
			instance = new SynMaps();
		return instance;
	}
	
	/**
	 * 
	 * 构造函数
	 */
	private SynMaps(){}
	
	/**
	 * 获取词word对应的编码
	 * @param word 
	 * @return 如果存在就返回对应编码，如果不存在就返回<code>null</code>
	 */
	public List<SynCode> getCode(String word) {
		return SynMaps.synonymitys.get(word);
	}
	
	/**
	 * 判断词word是否包含编码code
	 * @param word 一个词可能对应多个编码
	 * @param code
	 * @return
	 */
	public boolean checkCode(String word,String code) {
		List<SynCode> codeList = SynMaps.synonymitys.get(word);
		if(codeList != null && codeList.contains(new SynCode(code)))
			return true;
		return false;
	}
	
	/**
	 * 判断两个词是否同义
	 * @param word1
	 * @param word2
	 * @return
	 */
	public boolean isSynonymity(String word1,String word2)
	{
		List<SynCode> code1 = SynMaps.synonymitys.get(word1);
		List<SynCode> code2 = SynMaps.synonymitys.get(word2);
		if(code1 == null || code2 == null)
			return false;
		int size1 = code1.size();
		for(int i=0;i<size1;i++)
		{
			if(code2.contains(code1.get(i)))
			{
				return true;
			}
		}
		return false;
	}
}

